package file.search;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class SearchUtility {
	private String fileName = null;
	private Set<String> searchStringSet = null;
	private Map<String,Integer> freqMap = null;
	
	public SearchUtility(String fileName,Set<String> searchStringSet) {
		this.fileName = fileName;
		this.searchStringSet = searchStringSet;
		this.freqMap = new HashMap<String,Integer>();
		for (String key : searchStringSet) {
			put(key);
		}
	}
	
	private void put(String key){
		Integer value = freqMap.get(key);
		if(value == null){
			value = new Integer(0);
		}else{
			value +=1;
		}
		freqMap.put(key, value);
	}
	public Map<String,Integer> search(){
		FileReader reader = null;
		BufferedReader bRead = null;
		try{
			reader = new FileReader(this.fileName);
			bRead = new BufferedReader(reader);
			String buffer = null;
			while((buffer = bRead.readLine()) != null){
				String[] sentence = buffer.split(" ");
				for(String word : sentence ){
					word = word.trim();
					if(searchStringSet.contains(word.trim())){
						put(word.trim());
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(bRead != null){
				try {
					bRead.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(reader!=null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return this.freqMap;
	}
	public static void main(String[] args) {
		SearchUtility utility = new SearchUtility("out/model.xml", new HashSet<String>(Arrays.asList("<beans>","</beans>")));
		System.out.println(utility.search());
		
	}
}
